package me.leiusual.sharing.ui.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_nickname.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/28
 */
class MineNicknameFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: MineNicknameViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_nickname, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }
    toolbar.setOnMenuItemClickListener {
      when (it.itemId) {
        R.id.action_save -> {

          val nickname = edit_text_nickname.text.toString()
          viewModel.nicknameUpdate(nickname)

          true
        }
        else -> false
      }
    }

    edit_text_nickname.setText(viewModel.user.nickname)

    observeData()
  }

  private fun observeData() {
    viewModel.nicknameUpdate.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("nicknameUpdate = %s", it)
      when (it) {
        is Data.Loading -> {
        }
        is Data.Error -> {
          toast(it.error.message)
        }
        is Data.Success -> {
          toast("昵称修改成功")
          viewModel.userInfo()
        }
      }
    })

    viewModel.userInfo.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("userInfo = %s", it)
      when (it) {
        is Data.Loading -> {
        }
        is Data.Error -> {
          toast(it.error.message)
        }
        is Data.Success -> {
          findNavController().popBackStack()
        }
      }
    })
  }
}